package com.spider.silence.output;

import com.google.common.collect.Lists;
import com.spider.silence.utils.PropertiesUtil;

import java.io.IOException;
import java.util.LinkedList;

/**
 * Created by 夏茂轩 on 2017/1/11.
 */
public class FTPWriterPool {

    private static FTPWriterPool  instance= new FTPWriterPool();
    protected LinkedList<FTPWriter> pool = Lists.newLinkedList();

    /**
     * @author 夏茂轩
     * @date 2017/1/15 22:18
     * @description FTPWriterPool,初始化多个FTPWriter添加到池中
     */
    private   FTPWriterPool(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                loopCheck();
            }
        }).start();
        synchronized (pool){
            for(int i = 0; i<Integer.valueOf(PropertiesUtil.getVal("main.ftp.writer.pool.size")); i++){
                FTPWriter writer =new FTPWriter();
                pool.add(writer);
            }
            pool.notifyAll();
        }

    }

    /**
     * @author 夏茂轩
     * @date 2017/1/15 22:18
     * @description FTPWriterPool 单例
     * @return 返回初始化完成后的 FTPWriterPool
     */
    public  static FTPWriterPool getInstance(){
        return  instance;
    }

    /**
     * @author 夏茂轩
     * @date 2017/1/15 22:19
     * @description 返还使用完成的 FTPWriter
     * @param writer
     */
    public  void releaseWriter(FTPWriter writer) {
        if (writer != null) {
            synchronized (pool) {
                pool.addLast(writer);
                pool.notifyAll();
            }
        }
    }

    /**
     * @author 夏茂轩
     * @date 2017/1/15 22:20
     * @description 获取一个FTPWriter,该方法为阻塞方法***
     * @return FTPWriter
     * @throws InterruptedException 中断异常
     */
    public  FTPWriter fetchWriter() throws InterruptedException {
       synchronized (pool){
           while (pool.isEmpty()){
               pool.wait();
           }
           return pool.removeFirst();
       }
    }

    /**
     * @author 夏茂轩
     * @date 2017/1/15 22:21
     * @description 清空池
     */
    public void empty(){
        pool=Lists.newLinkedList();
    }

    public void loopCheck(){
        while (true){
            try {
                Thread.sleep((long) (200));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (pool){
                while (pool.isEmpty()){
                    try {
                       pool.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                FTPWriter writer=pool.removeFirst();
                try {
                    writer.ftpClient.sendNoOp();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                pool.addLast(writer);
                pool.notifyAll();
            }
        }
    }
}
